package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import object.ZcAdmin;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import dao.User2zcDao;
import utils.CookieUtil;


public class AutoLoginFilter implements Filter {
	
	
	private ApplicationContext ac;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req; 
		HttpServletResponse response = (HttpServletResponse)resp;
		//禁用filter的缓存
		response.setDateHeader("Expires", -1);  
        response.setHeader("Cache-Control", "no-cache");  
        response.setHeader("Pragma", "no-cache");
        
        //String uri=request.getRequestURI();
        //System.err.println(request.getRequestURI());
		HttpSession session = request.getSession(true); 
		ZcAdmin admin = (ZcAdmin)session.getAttribute("admin");
		
		boolean isLogin=request.getRequestURI().indexOf("login.jsp")!=-1;
		
		//如果封装的user不为空,说明已经登陆,则继续执行用户的请求.下面的就不处理了
		if(admin!=null){
			if(isLogin){
				response.sendRedirect("./admin/sendOrder.jsp");;
				return; 
			}
			chain.doFilter(request,response); 
			return; 
		}
		//user为空，说明用户还没有登陆,就尝试得到浏览器传送过来的Cookie
		Cookie cookies[] = request.getCookies(); 
		String[] cookieValues= null;
		if(cookies!=null){
			cookieValues=CookieUtil.readCookie(request);  
		}
	
		//如果cookieValue为空,也继续执行用户请求
		if(cookieValues==null){
			isLogin="0041".equals(request.getParameter("funcID"));
			if(isLogin){
				chain.doFilter(request,response);
				return; 
			}
			request.getRequestDispatcher("/web2zc/login.jsp").forward(request,response);
			return; 
		}else{
			//String path=request.getContextPath(); 
			if(cookieValues.length!=3){
				request.setAttribute("errorMsg", "进入方式非法");
	            request.getRequestDispatcher("/web2zc/login.jsp").forward(request,response);
	            return; 
			}
			//判断是否在有效期内,过期就删除Cookie
			long validTimeInCookie = new Long(cookieValues[1]); 
			if(validTimeInCookie < System.currentTimeMillis()){
				//删除Cookie
				CookieUtil.clearCookie(response); 
				request.setAttribute("errorMsg", "失效,请重新登陆");
				request.getRequestDispatcher("/web2zc/login.jsp").forward(request,response);
				return; 
			}

			//取出cookie中的用户名,并到数据库中检查这个用户名,
			String username = cookieValues[0]; 
			//根据用户名到数据库中检查用户是否存在
			//单例or线程绑定????
			//UserDAO ud = DaoImplFactory.getInstance();
			//User2zcDao dao=new User2zcDao();
			User2zcDao dao = (User2zcDao) ac.getBean("user2zcDao");
			
			admin = dao.getZcAdmin(username);
		
			//如果user返回不为空,就取出密码,使用用户名+密码+有效时间+ webSiteKey进行MD5加密
			if(admin!=null){
				String md5ValueInCookie = cookieValues[2]; 
				String md5ValueFromUser =CookieUtil.getMD5(admin.getWebName() + ":" + admin.getWebPwd()+ ":" + validTimeInCookie + ":" + CookieUtil.webKey); 
				//将结果与Cookie中的MD5码相比较,如果相同,写入Session,自动登陆成功,并继续用户请求
				if(md5ValueFromUser.equals(md5ValueInCookie)){
					session.setAttribute("admin", admin); 
					session.setAttribute("zcwx", 1);
					//chain.doFilter(request, response); 
					if(isLogin){
						response.sendRedirect("./admin/sendOrder.jsp");
						return; 
					}
					chain.doFilter(request,response); 
					return; 	
				}
			}else{
				//返回为空执行
				request.setAttribute("errorMsg", "验证错误");
				request.getRequestDispatcher("/web2zc/login.jsp").forward(request,response);
				return; 
			}
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		ServletContext context = config.getServletContext();
		ac = WebApplicationContextUtils.getWebApplicationContext(context);
	}
	
	
}
